﻿using CoreWebApiNuGet.ActionFilter;
using System.ComponentModel;
using System.Text.Json;

namespace CoreWebApiNuGet.ProgramExtend
{
    /// <summary>
    /// 添加控制器配置
    /// </summary>
    public static class AddControllersProgram
    {
        /// <summary>
        /// 添加mvc控制器服务。用于处理http请求响应
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddControllersAllocation(this IServiceCollection services)
        {
            services.AddControllers(options => {
                GlobalFilters.AddFilter(options.Filters);
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.WriteIndented = true;
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter("yyyy-MM-dd HH:mm:ss"));
            })
               // 支持 NewtonsoftJson
               .AddXmlDataContractSerializerFormatters(); //添加 XML 格式支持  AddXmlDataContractSerializerFormatters可以将匿名属性式化为xml，而AddXmlSerializerFormatters直接会忽略dynamic/object类型的属性。

            return services;
        }

        /// <summary>
        /// 自定义 DateTimeConverter 类来控制日期时间格式
        /// </summary>
        public class DateTimeConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
        {
            private readonly string _format;

            public DateTimeConverter(string format)
            {
                _format = format;
            }

            public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                return DateTime.Parse(reader.GetString());
            }

            public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
            {
                writer.WriteStringValue(value.ToString(_format));
            }
        }
    }
}
